﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using LUStationery.Model;
using LUStationery.DAO;
using LUStationery.Controller;

namespace LUStationery.Controller
{

    public class DepartmentControl
    {

        public Department getDepartmentByUserID(string userID)
        {
            UsersControl ucont = new UsersControl();
            User u = ucont.getUserByUserID(userID);
            Department depart = getDepartmentByDeptCode(u.DepartmentCode);
            return depart;
        }

        public Department getDepartmentByUserName(string username)
        {
            UsersControl ucont = new UsersControl();
            User u = ucont.getUserByUserName(username);
            Department depart = getDepartmentByDeptCode(u.DepartmentCode);
            return depart;
        }


        public int UpdateDeptInfo(Department depart, string collectionPoint,string representative) 
        {
            depart.CollectionPoint = collectionPoint;
            depart.Representative = representative;
            return update(depart);

        }

        public Department getDepartmentByDeptCode(string deptCode)
        {
            DepartmentDAO dDAO = new DepartmentDAO();
            IDataReader idr = dDAO.getDepartmentByDeptCode(deptCode);
            return DepartmentControl.convertIdrToDepartment(idr);
        }

        public int update(Department d)
        {
            DepartmentDAO dDAO = new DepartmentDAO();
            int flag = dDAO.updateDeptInfo(d.DeptCode, d.Representative, d.CollectionPoint);
            return flag;
        }



        protected static DepartmentList convertIdrToDepartmentList(IDataReader idr)
        {
            DepartmentList dList = new DepartmentList();
            while (idr.Read())
            {
                Department depart = new Department();
                depart.DeptCode = Convert.ToString(idr["department_code"]);
                depart.DeptName = Convert.ToString(idr["department_name"]);
                depart.Representative = Convert.ToString(idr["representative"]);
                depart.CollectionPoint = Convert.ToString(idr["collection_point"]);
                dList.Add(depart);
            }
            return dList;
        }

        protected static Department convertIdrToDepartment(IDataReader idr)
        {
            Department depart = new Department();
            while (idr.Read())
            {
                depart.DeptCode = Convert.ToString(idr["department_code"]);
                depart.DeptName = Convert.ToString(idr["department_name"]);
                depart.Representative = Convert.ToString(idr["representative"]);
                depart.CollectionPoint = Convert.ToString(idr["collection_point"]);
            }
            return depart;
        }

    }
}